const jwt = require('jsonwebtoken');
const UserModel = require('../models/userModel');

// 用户注册
const register = async (req, res) => {
  try {
    const { openid, userInfo } = req.body;
    
    if (!openid || !userInfo) {
      return res.status(400).json({
        success: false,
        message: '缺少必要信息'
      });
    }

    // 检查用户是否已存在
    const existingUser = await UserModel.findByOpenid(openid);
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户已存在'
      });
    }

    // 创建新用户
    const newUser = await UserModel.create({
      openid,
      ...userInfo
    });

    res.json({
      success: true,
      message: '注册成功',
      data: newUser
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 获取用户信息
const getUserInfo = async (req, res) => {
  try {
    const { openid } = req.user;

    const user = await UserModel.findByOpenid(openid);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 更新用户信息
const updateUserInfo = async (req, res) => {
  try {
    const { openid } = req.user;
    const updateData = req.body;

    const user = await UserModel.findByOpenid(openid);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 更新用户信息
    const updatedUser = await UserModel.update(openid, updateData);

    res.json({
      success: true,
      message: '更新成功',
      data: updatedUser
    });

  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

module.exports = {
  register,
  getUserInfo,
  updateUserInfo
}; 